package com.tao.config;

import com.tao.enums.ResultCode;
import com.tao.exception.APIException;
import com.tao.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ClassName GloablExceptionAdvice
 * @Author HETAO
 * @Date 2020/5/15 2:40
 */
@ControllerAdvice
@Slf4j
@ResponseBody
public class GloablExceptionAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        return new CommonResult(ResultCode.VALIDATE_FAILED,objectError.getDefaultMessage());
    }

    /**
     * 接口响应失败
     * @param e
     * @return
     */
    @ExceptionHandler(APIException.class)
    public CommonResult APIExceptionHandler(APIException e) {
        // 注意哦，这里返回类型是自定义响应体
        return new CommonResult<>(ResultCode.FAILED,e.getMessage());
    }
}


